import 'package:demo_app_video/commons/router/routes.dart';
import 'package:demo_app_video/dialog/episode.dart';
import 'package:demo_app_video/widgets/unlock_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_adcontent/flutter_adcontent.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class DramaDetails extends StatefulWidget {
  final Drama drama;

  const DramaDetails({Key? key, required this.drama}) : super(key: key);

  @override
  State<DramaDetails> createState() => _DramaDetailsState();
}

class _DramaDetailsState extends State<DramaDetails>
    with WidgetsBindingObserver {
  late ProVideoController controller;
  int currentIndex = 1; // 当前已播放的集数
  int newIndex = 1; // 当前最新的集数
  late Drama drama;

  var objData;

  @override
  void initState() {
    drama = widget.drama;
    super.initState();
    WidgetsBinding.instance.addObserver(this); // Add observer
    controller = ProVideoController();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // Remove observer
    controller.dispose();
    print('销毁');
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // if (state == AppLifecycleState.paused) {
    //   controller.pause(); // Pause video when app goes to background
    // } else if (state == AppLifecycleState.resumed) {
    //   controller.resume(); // Resume video when app comes to foreground
    // }
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Scaffold(
        backgroundColor: Color(0xff000000),
        bottomNavigationBar: Container(
          height: 65.h,
          color: Color(0xff333333),
          child: Text(
            '- 海量短剧免费看 -',
            style: TextStyle(
                color: Color(0xffF9F9F9),
                fontSize: 16.sp,
                fontWeight: FontWeight.bold),
          ),
          alignment: Alignment.center,
        ),
        body: Stack(children: [
          DramaWidget(
            controller: controller,
            width: size.width,
            height: size.height,
            id: drama.id,
            index: drama.index,
            groupId: "1",
            hideTopInfo: true,
            hideBottomInfo: true,
            setBottomOffset: 0,
            hideLikeButton: true,
            hideFavorButton: true,
            hideMore: true,
            unlockAdMode: 1, // 0:SDK 广告解锁 1：自定义广告解锁
            unlockCount: 2,
            unlockFlowListener: UnlockFlowListener(
              unlockFlowStart: (Drama drama) {
                // 解锁流程开始
                print(
                    'VideoPlayListener unlockFlowStart: ${drama.id}:${drama.title}:${drama.index}');
                showUnlockDialog(drama);
              },
              unlockFlowEnd: (int? errCode, String? errMsg) {
                // 解锁流程结束
                print(
                    'VideoPlayListener unlockFlowEnd: errCode:$errCode errMsg:$errMsg');
                if (errCode != 200) {
                  // 解锁失败
                  backIndex();
                } else {
                  // 解锁成功
                }
              },
              showCustomAd: (Drama drama) {
                // 显示自定义广告
                print(
                    'VideoPlayListener showCustomAd: ${drama.id}:${drama.title}:${drama.index}');
                showCustomAd();
              },
            ),
            videoPlayListener: VideoPlayListener(
              onDJXPageChange: (Drama dramavalue) {
                drama = dramavalue;
                setState(() {});
                // 视频切换
                print(
                    'VideoPlayListener onDJXPageChange: ${drama.id}:${drama.title}:${drama.index}');
              },
              onDJXVideoPlay: (Drama drama) {
                // 视频播放开始
                print(
                    'VideoPlayListener onDJXVideoPlay: ${drama.id}:${drama.title}:${drama.index}');
                currentIndex = drama.index;
                setState(() {
                  newIndex = drama.index;
                });
              },
              onDJXVideoPause: (Drama drama) {
                // 视频暂停
                print(
                    'VideoPlayListener onDJXVideoPause:  ${drama.id}:${drama.title}:${drama.index}');
              },
              onDJXVideoContinue: (Drama drama) {
                // 视频继续
                print(
                    'VideoPlayListener onDJXVideoContinue: ${drama.id}:${drama.title}:${drama.index}');
              },
              onDJXVideoCompletion: (Drama drama) {
                // 视频播放完成
                print(
                    'VideoPlayListener onDJXVideoCompletion: ${drama.id}:${drama.title}:${drama.index}');
              },
              onDJXVideoOver: (Drama drama) {
                // 视频结束
                print(
                    'VideoPlayListener onDJXVideoOver: ${drama.id}:${drama.title}:${drama.index}');
              },
              onDJXVideoClose: () {
                // 视频关闭
                print('VideoPlayListener onDJXVideoClose');
              },
              onDJXSeekTo: (duration) {
                // 拖动进度
                print("VideoPlayListener onDJXSeekTo:$duration");
              },
              onDurationChange: (duration) {
                // 播放进度
                print("VideoPlayListener onDurationChange:$duration");
              },
              onError: (int? errCode, String? errMsg) {
                // 播放错误
                print("VideoPlayListener onError:$errCode:$errMsg");
              },
            ),
          ),
          Positioned(
            child: GestureDetector(
              child: Container(
                child: Row(
                  children: [
                    Container(
                      padding: EdgeInsets.all(12.w),
                      width: 40.w,
                      height: 40.w,
                      child: Image.asset(
                        'images/back_arrow.png',
                        width: 16.w,
                        color: Colors.white,
                      ),
                    ),
                    Text(
                      '第${newIndex}集',
                      style:
                          TextStyle(color: Color(0xffFFFFFF), fontSize: 16.sp),
                    )
                  ],
                ),
              ),
              onTap: () {
                Routes().popNowPage(context);
              },
            ),
            top: MediaQuery.of(context).padding.top,
          ),
          Positioned(
            child: Container(
              width: 360.w,
              height: 130.h,
              padding: EdgeInsets.only(left: 12.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '${drama.title}',
                    style: TextStyle(
                        color: Color(0xffFFFFFF),
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 6.h),
                    width: 300.h,
                    child: Text(
                      '${drama.desc}',
                      style:
                          TextStyle(color: Color(0xffFEFEFE), fontSize: 12.sp),
                      maxLines: 3,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  InkWell(
                    onTap: () => to_xuanzjij(),
                    child: Container(
                      margin: EdgeInsets.only(top: 16.h),
                      width: 240.w,
                      child: Text(
                        '选集.${drama.total}集 >',
                        style: TextStyle(
                            color: Color(0xffFFFFFF), fontSize: 12.sp),
                      ),
                    ),
                  )
                ],
              ),
            ),
            bottom: MediaQuery.of(context).padding.bottom + 20.h,
          ),
        ]));
  }

  //选集弹窗
  to_xuanzjij() async {
    //调用选集弹窗
    var resultData = await showModalBottomSheet<dynamic>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context1, state) {
          return EpisodeDialog(
            drama: drama,
            currentIndex: currentIndex,
          );
        });
      },
    );
    if (resultData != '' && resultData != null) {
      controller.setCurrentIndex(resultData);
    }
  }

  Future<void> setCustomAdOnShow() async {
    controller.setCustomAdOnShow("1000");
  }

  /// 调用自定义的广告
  Future<void> showCustomAd() async {
    // 假设广告调用成功
    // 1、先设置广告价格
    setCustomAdOnShow();
    // await Future.delayed(const Duration(seconds: 3));
    // 2、设置激励结果
    setCustomAdOnReward(true);
  }

  Future<void> showUnlockDialog(Drama drama) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => UnlockDialog(
        title: '${drama.title} ',
        indexText: '第${drama.index}集',
        unlockText: '免费解锁 2 集',
        tipText: "解锁还能提高红包奖励哦~",
        onClose: () {
          Navigator.pop(context);
          unLockDrama(drama, true);
        },
        onUnlock: () {
          Navigator.pop(context);
          unLockDrama(drama, false);
        },
      ),
    );
  }

  void backIndex() {
    controller.setCurrentIndex(currentIndex);
  }

  Future<void> setCustomAdOnReward(bool verify) async {
    controller.setCustomAdOnReward(verify, extraData: {"key": "value"});
    print('VideoPlayListener setCustomAdOnReward $verify');
  }

  /// 解锁短剧
  Future<void> unLockDrama(Drama drama, bool cancel) async {
    controller.unLock(drama.id, 2, cancel);
  }
}
